//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
// Copyright 2012 Microsoft Corporation. All Rights Reserved
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.   
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
//--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

namespace Preflight.Core.Execution
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;
    using Model;

    public class ExecuteVerificationTask : IDisposable 
    {
        private readonly TimeSpan executionTimeout;
        private readonly Stopwatch executionStopwatch = new Stopwatch();
        private VerificationResult result;

        public ExecuteVerificationTask(IVerification verification, TimeSpan executionTimeout)
        {
            this.executionTimeout = executionTimeout;
            this.Verification = verification;
        }

        public IVerification Verification
        {
            get;
            private set;
        }

        private Task Task
        {
            get;
            set;
        }

        private CancellationTokenSource CancellationTokenSource
        {
            get;
            set;
        }

        public void Start()
        {
            if (this.Task != null)
            {
                throw new InvalidOperationException("Task has already started!");
            }

            this.CancellationTokenSource = new CancellationTokenSource();
            this.Task = Task.Factory.StartNew(this.Execute, this.CancellationTokenSource.Token);
        }

        public VerificationResult GetResult()
        {
            if (this.Task == null)
            {
                throw new InvalidOperationException("Task has not yet started");
            }

            if (this.result == null)
            {
                if (this.TaskHasExceededAllowedTime())
                {
                    this.CancellationTokenSource.Cancel();
                    this.SetResultAsTimedout();
                }
                else if (this.TaskHasFaulted())
                {
                    this.SetResultAsFaulted();
                }
            }

            return this.result;
        }

        public void Dispose()
        {
            if (this.Task != null)
            {
                try
                {
                    this.Task.Dispose();
                }
                catch (Exception exception)
                {
                    Log.LogVerbose("Could not dispose task because: {0}", exception);
                }
            }

            if (this.CancellationTokenSource != null)
            {
                try
                {
                    this.CancellationTokenSource.Dispose();
                }
                catch (Exception exception)
                {
                    Log.LogVerbose("Could not dispose cancellation token source because: {0}", exception);
                }
            }            
        }

        private void SetResultAsFaulted()
        {
            var result = new VerificationResult(this.Verification);
            result.AddException(this.Task.Exception);
        }

        private void SetResultAsTimedout()
        {
            var result = new VerificationResult(this.Verification);
            result.AddMessage(MessageType.Error, Messages.VerificationHasTimedOut);
            this.result = result;
        }

        private bool TaskHasFaulted()
        {
            return this.Task.IsFaulted;
        }

        private bool TaskHasExceededAllowedTime()
        {
            return this.Task.Status == TaskStatus.Running && this.executionStopwatch.Elapsed > this.executionTimeout;
        }

        private void Execute()
        {
            Log.LogVerbose("Executing Test: {0} Category: {1}", this.Verification.Name, this.Verification.Category);
            this.executionStopwatch.Start();
            this.result = this.Verification.Run();
            this.executionStopwatch.Stop();
            this.result.ExecutionTime = this.executionStopwatch.Elapsed;
            Log.LogVerbose(
                "Finished Test: {0} Category: {1}. Passed: {2}. ExecutionTime: {3}",
                this.Verification.Name,
                this.Verification.Category,
                this.result.Passed,
                this.result);
        }
    }
}
